import sys
import pprint
import string
import sys
import cgi
import types
import traceback
import urllib

import genx_helpers
genx_helpers.add_module('pyecs')

import genx_metaweb
import genx_transfill
import genx_errors
import bm_text
import bm_extract
import bm_cfg

import ecs

searchd = {
	"title" : "Music on CD",
	"source" : "Amazon.com",
	"templated" : {
		"gencard-uf" : {
			"title" : "GenCard",
			"title_full" : "GenCard for Microformats",
			"caps" : [ 
				genx_helpers.CAP_GENCARD, 
				genx_helpers.CAP_HTML, 
				genx_helpers.CAP_MICROFORMATS, 
				genx_helpers.CAP_HITEM,
			],
		},
	},
}

CACHE = False
MAX_RESULTS = 30

def query(cfg, searchd, name, application, retry = 0):
	amazon = ecs.AmazonECS(
		AccessKeyID = bm_cfg.cfg.as_string("amazon.AccessKeyID"),
		Locale = bm_cfg.cfg.as_string("amazon.Locale"),
		AssociateTag = bm_cfg.cfg.as_string("amazon.AssociateTag"),
	)

	count = 0
	max = bm_cfg.cfg.as_string("amazon.max", MAX_RESULTS)

	for resultd in amazon.iterMusicByKeywords(Keywords = name, ResponseGroup = amazon.RG_Large, Format = "CD"):
		count += 1

		iid = application.MakeIID('%s@amazon.books' % bm_extract.extract(resultd, 'ASIN'))
		rd = {
			genx_helpers.KEY_IID : iid,
			genx_helpers.KEY_TITLE_SHORT : bm_extract.as_string(resultd, "Title"),
			genx_helpers.KEY_TITLE_FULL : bm_extract.as_string(resultd, "Title"),
			"artist" : bm_extract.as_string(resultd, "Artist") or bm_extract.as_string(resultd, "Actor"),
		}

		for keyt in [ 
			( 'OriginalReleaseDate', 'released', ),
			( 'Publisher', 'publisher', ),
			( 'UPC', 'UPC', ),
			( 'ISBN', 'ISBN', ),

			( 'Label', 'Label', ),
			( 'DetailPageURL', 'amazon_uri', ),
		]:
			value = bm_extract.as_string(resultd, keyt[0])
			if value and type(value) in types.StringTypes and value.strip():
				rd[keyt[1]] = value.strip()

		review = bm_extract.as_string(resultd, "EditorialReviews.EditorialReview.Content[0]")
		if review:
			review = bm_text.scrub_html(review)
			review = review.strip()
			if review:
				rd["description"] = review

		image_uri = bm_extract.as_string(resultd, "TinyImage.URL", separator = None)
		if image_uri:
			rd[genx_helpers.KEY_IMAGE_URI] = image_uri

		tracks = bm_extract.extract(resultd, "Track")
		if tracks and type(tracks) == types.ListType:
			rd["tracks"] = tracks

		rd[genx_helpers.KEY_TITLE_LIST] = "%s - %s%s" % (
			rd[genx_helpers.KEY_TITLE_FULL] or rd[genx_helpers.KEY_TITLE_SHORT] or "[no title]",
			rd["artist"] or "[no artist]",
			rd.get("released") and ( " [%s]" % rd["released"][:4] ) or "",
		)

		yield	rd

		if count >= max:
			break

